package com.gxa.servlet.getmoney;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.pojo.Result;
import com.gxa.pojo.getmoneypojo.ShouYing;
import com.gxa.service.getmoneysevice.GetMoneyService;
import com.gxa.service.getmoneysevice.getMoneyServiceImpl.GetMoneyServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/getMoneyServlet")
public class GetMoneyServlet extends HttpServlet {


    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json;charset=UTF-8");

        //1.获取前端请求
        //因为request.getreader（）方法只能读一次，采用下面几行代码
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(req.getInputStream(),"UTF-8"));
        StringBuilder json = new StringBuilder();
        String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
            json.append(inputStr);
        }
        //1.1这是将json转化为字符串的形式
        String jsonString = json.toString();
        System.out.println(jsonString);
        ObjectMapper objectMapper = new ObjectMapper();
        ShouYing shouYing = objectMapper.readValue(jsonString, ShouYing.class);

        //获取条形码数据
        String barcode = shouYing.getBarcode();
        int count = shouYing.getCount();

        //根据条形码查名称和单价
        GetMoneyService getMoneyService = new GetMoneyServiceImpl();
        String name = getMoneyService.findName(barcode);  //查到商品名称
        float price = getMoneyService.findPrice(barcode); //查到商品单价

        Boolean aBoolean = getMoneyService.addGoods(barcode, count);
        //设置相关的成员
        shouYing.setGoods_name(name);
        shouYing.setDanJia(price);


        PrintWriter writer = resp.getWriter();
        Map<String,Object> map = new HashMap<>();
        String fl = null;
        if(shouYing !=null){
            map.put("result", Result.ok("success",shouYing));
          fl = objectMapper.writeValueAsString(map);
        }else{
            map.put("result",Result.error());
            fl = objectMapper.writeValueAsString(map);
        }

        writer.write(fl);
        writer.flush();
        writer.close();
        streamReader.close();
    }
}